import React from 'react';
import Simditor from 'simditor';
import 'simditor/styles/simditor.css';
import './rich-editor.styl';
/**
 * 通用富文本编辑器 依赖jquery
 */
class RichEditor extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.loadEditor();
  }

  componentWillReceiveProps(nextProps) { // 避免富文本每次变化的时候都进行this.simiditor.setValue()操作
    let detailChange = this.props.defaultDetail !== nextProps.defaultDetail;
    if (!detailChange) return false;
    this.simiditor.setValue(nextProps.defaultDetail);
  }

  loadEditor() {
    let element = this.refs['textarea'];
    this.simiditor = new Simditor({
      textarea: element,
      defaultValue: this.props.placeholder || '请输入内容',
      upload: {
        url: '/manage/product/richtext_img_upload.do',
        defaultImage: '',
        fileKey: 'upload_file'
      }
    });
    this.bindEditorEvent();
  }

  bindEditorEvent() {
    this.simiditor.on('valuechanged', e => {
      this.props.onValueChange(this.simiditor.getValue());
    });
  }

  render() {
    return (
      <div className="rich-editor">
        <textarea ref="textarea"></textarea>
      </div>
    );
  }
}

export default RichEditor;